package main

import (
	"context"
	"flag"
	"fmt"
	"os"
	"os/signal"
	"syscall"

	"xagent/internal/actors"
	"xagent/internal/distributed"
	"xagent/internal/providers"
	protov1 "xagent/proto/v1"

	"github.com/asynkron/protoactor-go/actor"
)

func main() {
	// Parse command line flags
	port := flag.Int("port", 8090, "Port to listen on")
	name := flag.String("name", "node1", "Node name")
	flag.Parse()

	// Create actor system
	system := actor.NewActorSystem()

	// Create cluster manager
	address := fmt.Sprintf("localhost:%d", *port)
	config := &distributed.Config{
		Address: address,
		// ... 其他必要的配置字段
	}
	clusterManager, err := distributed.NewClusterManager(system, config)
	if err != nil {
		fmt.Printf("Failed to create cluster manager: %v\n", err)
		os.Exit(1)
	}

	// Create LLM provider
	llmConfig := &providers.ProviderConfig{
		Type:    "anthropic",
		Model:   "claude-2",
		APIKey:  os.Getenv("ANTHROPIC_API_KEY"),
		BaseURL: "https://api.anthropic.com/v1",
	}
	llmProvider, err := providers.NewOpenAIProvider(llmConfig)
	if err != nil {
		fmt.Printf("Failed to create LLM provider: %v\n", err)
		os.Exit(1)
	}

	// Create team coordinator
	coordinator := actors.NewTeamCoordinator(*name, system, llmProvider)
	coordinatorPID, err := system.Root.SpawnNamed(actor.PropsFromProducer(func() actor.Actor {
		return coordinator
	}), "coordinator")
	if err != nil {
		fmt.Printf("Failed to spawn coordinator: %v\n", err)
		os.Exit(1)
	}

	// Create context with cancellation
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	// Start cluster manager
	if err := clusterManager.Start(ctx); err != nil {
		fmt.Printf("Failed to start cluster manager: %v\n", err)
		os.Exit(1)
	}

	// Initialize coordinator
	coordinator.Initialize()

	// Example: Create and assign a task
	task := &protov1.Task{
		Id:          "task-1",
		Name:        "Example Task",
		Description: "This is an example task",
		Status:      protov1.TaskStatus_TASK_STATUS_PENDING,
	}
	system.Root.Send(coordinatorPID, task)

	// Wait for interrupt signal
	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
	<-sigChan

	// Stop cluster manager
	if err := clusterManager.Stop(); err != nil {
		fmt.Printf("Failed to stop cluster manager: %v\n", err)
	}
}
